package com.lemon.smartsafety.ui.activity.fire.item;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.file.MySPUtilsName;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.mode.adapter.LampMode;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.FireCompanyBaseScore;
import com.lemon.smartsafety.result.fire.SuperviseCompanyDetail;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.activity.fire.item.statistics.CensusStatisticsActivity;
import com.lemon.smartsafety.ui.activity.fire.item.statistics.CompanyStatisticsShowActivity;
import com.lemon.smartsafety.ui.activity.fire.item.statistics.DeviceStatisticsActivity;
import com.lemon.smartsafety.ui.activity.fire.item.statistics.PersonalStatisticsActivity;
import com.lemon.smartsafety.ui.activity.fire.item.statistics.ProjectStatisticsActivity;
import com.lemon.smartsafety.ui.activity.fire.item.statistics.SafeStatisticsActivity;
import com.lemon.smartsafety.ui.adapter.fire.LampAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LocationUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.ViewFireTop;
import com.lemon.smartsafety.view.ViewRadarTitle;
import com.lemon.smartsafety.view.ViewTag;
import com.lemon.smartsafety.view.dialog.DialogRadarView;
import com.lemon.smartsafety.view.list.MyListView;
import com.lemon.smartsafety.view.radar.RadarView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/8/9 11:33
 * 修改人：Fargo
 * 修改时间：2016/8/9 11:33
 * 修改备注：   监督管理 某一单位信息
 */
public class FirefightingManageCompanyActivity extends NewBaseActivity {

    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.listView)
    MyListView listView;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.fireTop)
    ViewFireTop fireTop;
    @Bind(R.id.radarView)
    RadarView radarView;
    @Bind(R.id.viewRadarTitle)
    ViewRadarTitle viewRadarTitle;
    @Bind(R.id.viewTag)
    ViewTag viewTag;
    @Bind(R.id.viewFireCompanyNone)
    ViewFireCompanyNone viewFireCompanyNone;


    private LampAdapter lampAdapter;
    private List<LampMode> mList;
    private LampMode lampMode;

    private DialogRadarView dialogRadarView;

    private SuperviseCompanyResult.ResultEntity resultEntity;
    private FireCompanyBaseScore fireCompanyBaseScore;
    private LocationUtil locationUtil;

    private SuperviseCompanyDetail superviseCompanyDetail;

    //是否签到成功
    private boolean isSign = false;


    private String[] titles;
    private double[] data1;
    private double[] data2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void getBundleArgs() {
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_firefighting_manage_company;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("监督管理");
    }

/*    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_firesign, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        Log.e("onPrepareOptionsMenu", "onPrepareOptionsMenu");
        menu.clear();
        if (isSign) {
            getMenuInflater().inflate(R.menu.menu_firesign_ok, menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_firesign, menu);
        }

        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_firesign) {
            LogUtils.LOGE("监督签到");
            locationUtil.getLoacation(new LocationUtil.CallBackInterface() {
                @Override
                public void callBackFunction() {
                    LogUtils.LOGE("定位地理位置");
                    signHttp();
                }
            });
        }
        return super.onOptionsItemSelected(item);
    }*/

    @Override
    protected void initView() {
        fireTop.setAllBg(R.color.main_gray);
        fireTop.setTitleContent(resultEntity.getCompanyName());
        fireTop.setTitleSubContent("综合评分");
        fireTop.setNum1Content("0");
        fireTop.setNum2Content("/0");
        fireTop.setNum1Color(R.color.colorAppRed);
        fireTop.setNum2Color(R.color.colorAppBlue);

        mList = new ArrayList<>();

        lampAdapter = new LampAdapter(mActivity, mList);
        listView.setAdapter(lampAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mList.get(position).getTitle().contains("人员履职")) {
                    intent = new Intent(mActivity, PersonalStatisticsActivity.class);

                } else if (mList.get(position).getTitle().contains("检查项目")) {
                    intent = new Intent(mActivity, ProjectStatisticsActivity.class);

                } else if (mList.get(position).getTitle().contains("安全管理")) {
                    intent = new Intent(mActivity, SafeStatisticsActivity.class);

                } else if (mList.get(position).getTitle().contains("基本信息")) {
                    //intent = new Intent(mActivity, CompanyStatisticsActivity.class);
                    intent = new Intent(mActivity, CompanyStatisticsShowActivity.class);
                } else if (mList.get(position).getTitle().contains("户籍化")) {
                    intent = new Intent(mActivity, CensusStatisticsActivity.class);

                } else if (mList.get(position).getTitle().contains("设施完好")) {
                    int mTagWidth = viewTag.getLineTag().getWidth();
                    MySPUtilsName.saveSP(MySPUtilsName.GET_WIDTH, mTagWidth);
                    intent = new Intent(mActivity, DeviceStatisticsActivity.class);

                } else {
                    return;
                }

                bundle = new Bundle();
                bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                for (int i = 0; i < superviseCompanyDetail.getMyCompanyScoreList().size(); i++) {
                    if (mList.get(position).getTitle().contains(superviseCompanyDetail.getMyCompanyScoreList().get(i).getTargetName())) {
                        bundle.putSerializable(BundleKey.FIRE_COMPANY_PRO_CODE, superviseCompanyDetail.getMyCompanyScoreList().get(i));
                        break;
                    }
                }

                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        scrollView.smoothScrollTo(0, 0);
        locationUtil = new LocationUtil(mActivity);

    }

    @Override
    protected void initHttp() {
        initTopHttp();
        getCompanyHttp();
    }

    @Override
    protected void initList() {

    }

    @Override
    protected void loadList() {

    }

    @Override
    protected void refreshView() {
        mList.clear();
        mList.add(new LampMode(1, "各项指标"));
        for (int i = 0; i < superviseCompanyDetail.getMyCompanyScoreList().size(); i++) {
            mList.add(new LampMode(0, superviseCompanyDetail.getMyCompanyScoreList().get(i).getTargetName() + "(" + superviseCompanyDetail.getMyCompanyScoreList().get(i).getScore() + ")", "", true, FirefightingUtil.getScoreImgCircleColor(superviseCompanyDetail.getMyCompanyScoreList().get(i).getStatus())));
        }
        lampAdapter.notifyDataSetChanged();

        try {
            titles = new String[superviseCompanyDetail.getMyCompanyScoreList().size()];
            data1 = new double[superviseCompanyDetail.getMyCompanyScoreList().size()];
            data2 = new double[superviseCompanyDetail.getMyCompanyScoreList().size()];

            for (int i = 0; i < superviseCompanyDetail.getMyCompanyScoreList().size(); i++) {
                titles[i] = superviseCompanyDetail.getMyCompanyScoreList().get(i).getTargetName();
                if (superviseCompanyDetail.getMyCompanyScoreList().get(i).getScore().equals("0")) {
                    data1[i] = 1;
                } else {
                    data1[i] = Double.parseDouble(superviseCompanyDetail.getMyCompanyScoreList().get(i).getScore());
                }
            }

            for (int i = 0; i < superviseCompanyDetail.getAllCompanyScoreList().size(); i++) {
                if (superviseCompanyDetail.getAllCompanyScoreList().get(i).getScore().equals("0")) {
                    data2[i] = 1;
                } else {
                    data2[i] = Double.parseDouble(superviseCompanyDetail.getAllCompanyScoreList().get(i).getScore());
                }
            }

            radarView.setTitles(titles);
            radarView.setDataOne(data1);
            radarView.setDataTwo(data2);
            radarView.setCount(titles.length);
            radarView.resetShow();

            viewRadarTitle.setVisibility(View.VISIBLE);
            viewRadarTitle.setTitle1("本单位:");
            viewRadarTitle.setTitleImg1(ContextCompat.getColor(mActivity, R.color.txt_color2));

            viewRadarTitle.setTitle2("所有:");
            viewRadarTitle.setTitleImg2(ContextCompat.getColor(mActivity, R.color.txt_color3));

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

    }


    /**
     * @param msg  列表请求失败
     */
    private void errorList(String msg){
        if (CommonUtil.listIsEmpty(mList)) {
            viewFireCompanyNone.setVisibility(View.VISIBLE);
            viewFireCompanyNone.setContent(msg);
            viewFireCompanyNone.setSearch("重试");
            listView.setVisibility(View.GONE);
            viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                @Override
                public void click() {
                    LogUtils.LOGE("点击了重试");
                    getCompanyHttp();
                }
            });
        } else {
            viewFireCompanyNone.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void callFinish() {
        mActivity.finish();
    }


    @OnClick({R.id.radarView})
    public void onButtonClick(View v) {
        switch (v.getId()) {

            case R.id.radarView:
                if (dialogRadarView == null) {
                    dialogRadarView = new DialogRadarView(mActivity);
                }
                if (titles != null) {
                    dialogRadarView.setTitles(titles);
                }
                if (data1 != null) {
                    dialogRadarView.setData1(data1);
                }
                if (data2 != null) {
                    dialogRadarView.setData2(data2);
                }

                dialogRadarView.setStrTitle1("本单位:");
                dialogRadarView.setStrTitle2("所有:");
                dialogRadarView.init(mActivity);
                break;
            default:
                break;
        }
    }


    public void initTopHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("radio_code", "");

        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_score), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                fireCompanyBaseScore = mGson.fromJson(mGson.toJson(baseMode.getResult()), FireCompanyBaseScore.class);
                                initTopScore();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            errorList(baseMode.getMsg());
                            ToastUtil.show(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }




    /**
     * 初始化顶部信息
     */
    private void initTopScore() {
        fireTop.setNum1Color(FirefightingUtil.getScoreTextColor(fireCompanyBaseScore.getStatus()));
        fireTop.setNum2Color(R.color.colorAppBlue);
        fireTop.setNum1Content(fireCompanyBaseScore.getCompanyScore());
        fireTop.setNum2Content("/" + fireCompanyBaseScore.getAvgScore());

    }


    /**
     * 监督签到
     */
    public void signHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("latitude", locationUtil.getmLat());
        params.put("longitude", locationUtil.getmLng());
        params.put("position", locationUtil.getmAddress());

        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Sign_in), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            ToastUtil.show(baseMode.getMsg());
                            isSign = true;
                            invalidateOptionsMenu();
                        } else {
                            ToastUtil.show(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


    /**
     * 监督管理（单位）
     */
    public void getCompanyHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());

        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_supervise_company_detail), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            try {
                                superviseCompanyDetail = mGson.fromJson(mGson.toJson(baseMode.getResult()), SuperviseCompanyDetail.class);
                                if (!CommonUtil.objIsEmpty(superviseCompanyDetail)) {
                                    refreshView();
                                } else {
                                    mHUDUtil.showErrorTip("出错了");
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtil.show(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


}
